// API服务函数
// REF: API-USER-0042@v1.0

import { 
  apiClient, 
  ApiResponse, 
  PaginatedResponse,
  User,
  LoginRequest,
  LoginResponse,
  UpdateUserRequest,
  ChangePasswordRequest,
  CreateUserRequest,
  UserSession
} from '@/lib/api';

// 健康检查
export const healthCheck = async (): Promise<ApiResponse> => {
  const response = await apiClient.get('/health');
  return response.data;
};

// 认证相关API
export const authApi = {
  // 用户登录
  login: async (data: LoginRequest): Promise<ApiResponse<LoginResponse>> => {
    const response = await apiClient.post('/auth/login', data);
    return response.data;
  },

  // 用户登出
  logout: async (): Promise<ApiResponse> => {
    const response = await apiClient.post('/auth/logout');
    return response.data;
  },

  // 刷新token
  refresh: async (refreshToken: string): Promise<ApiResponse<{ access_token: string }>> => {
    const response = await apiClient.post('/auth/refresh', {
      refresh_token: refreshToken
    });
    return response.data;
  },

  // 验证token
  verify: async (): Promise<ApiResponse<User>> => {
    const response = await apiClient.get('/auth/verify');
    return response.data;
  }
};

// 用户相关API
export const userApi = {
  // 获取当前用户信息
  getCurrentUser: async (): Promise<ApiResponse<User>> => {
    const response = await apiClient.get('/user/me');
    return response.data;
  },

  // 更新当前用户信息
  updateCurrentUser: async (data: { nickname?: string; realName?: string; phone?: string }): Promise<ApiResponse<User>> => {
    const response = await apiClient.put('/user/me', data);
    return response.data;
  },

  // 修改密码
  changePassword: async (data: ChangePasswordRequest): Promise<ApiResponse> => {
    const response = await apiClient.put('/user/password', data);
    return response.data;
  },

  // 获取用户会话列表
  getSessions: async (): Promise<ApiResponse<UserSession[]>> => {
    const response = await apiClient.get('/user/sessions');
    return response.data;
  },

  // 删除指定会话
  deleteSession: async (sessionId: string): Promise<ApiResponse> => {
    const response = await apiClient.delete(`/user/sessions/${sessionId}`);
    return response.data;
  }
};

// 管理员相关API
export const adminApi = {
  // 获取用户列表
  getUsers: async (params?: {
    page?: number;
    per_page?: number;
    role?: string;
    status?: string;
    search?: string;
  }): Promise<PaginatedResponse<User>> => {
    const response = await apiClient.get('/admin/users', { params });
    return response.data;
  },

  // 创建用户
  createUser: async (data: CreateUserRequest): Promise<ApiResponse<User>> => {
    const response = await apiClient.post('/admin/users', data);
    return response.data;
  },

  // 获取用户详情
  getUser: async (userId: number): Promise<ApiResponse<User>> => {
    const response = await apiClient.get(`/admin/users/${userId}`);
    return response.data;
  },

  // 更新用户信息
  updateUser: async (userId: number, data: UpdateUserRequest): Promise<ApiResponse<User>> => {
    const response = await apiClient.put(`/admin/users/${userId}`, data);
    return response.data;
  },

  // 删除用户
  deleteUser: async (userId: number): Promise<ApiResponse> => {
    const response = await apiClient.delete(`/admin/users/${userId}`);
    return response.data;
  },

  // 重置用户密码
  resetPassword: async (userId: number, newPassword: string): Promise<ApiResponse> => {
    const response = await apiClient.put(`/admin/users/${userId}/password`, {
      new_password: newPassword
    });
    return response.data;
  },

  // 批量删除用户
  batchDeleteUsers: async (userIds: number[]): Promise<ApiResponse> => {
    const response = await apiClient.delete('/admin/users/batch', {
      data: { user_ids: userIds }
    });
    return response.data;
  },

  // 更新用户上传权限
  updateUploadPermission: async (userId: number, canUpload: boolean): Promise<ApiResponse> => {
    const response = await apiClient.put(`/users/${userId}/upload-permission`, {
      canUploadFiles: canUpload
    });
    return response.data;
  },

  // 批量更新用户上传权限
  batchUpdateUploadPermission: async (userIds: number[], canUpload: boolean): Promise<ApiResponse> => {
    const response = await apiClient.put('/users/batch-upload-permission', {
      userIds,
      canUploadFiles: canUpload
    });
    return response.data;
  }
};

// 虚拟网盘相关API (静态数据)
// 网盘文件接口类型定义
export interface NetdiskFile {
  id: number;
  name: string;
  type: 'file' | 'folder';
  size?: number;
  modified: string;
  owner: string;
  shared: boolean;
  favorite?: boolean;
  parentId?: number;
  extension?: string;
}

export interface FileListResponse {
  files: NetdiskFile[];
  total: number;
  page: number;
  pageSize: number;
}

export interface StorageStats {
  total: number;
  used: number;
  available: number;
  files: number;
  folders: number;
}

// 网盘API
export const driveApi = {
  // 获取文件列表
  getFiles: async (parentId?: number, page: number = 1, pageSize: number = 20): Promise<ApiResponse<FileListResponse>> => {
    const params = new URLSearchParams({
      page: page.toString(),
      pageSize: pageSize.toString()
    });
    
    if (parentId !== undefined) {
      params.append('parentId', parentId.toString());
    }
    
    const response = await apiClient.get(`/netdisk/files?${params}`);
    const result = response.data;
    
    // 转换后端数据结构为前端期望的格式
    if (result.success && result.data && result.data.items) {
      const transformedFiles = result.data.items.map((item: any) => ({
        id: item.id,
        name: item.name,
        type: item.isFolder ? 'folder' : 'file' as 'file' | 'folder',
        size: item.fileSize,
        modified: item.updatedAt || item.createdAt,
        owner: 'current_user', // 临时值，后续可从用户信息获取
        shared: false, // 临时值，后续可从分享信息获取
        favorite: item.isFavorite || false,
        parentId: item.parentId,
        extension: item.fileExtension
      }));
      
      return {
        ...result,
        data: {
          files: transformedFiles,
          total: result.data.total,
          page: result.data.page,
          pageSize: result.data.pageSize
        }
      };
    }
    
    return result;
  },

  // 创建文件夹
  createFolder: async (name: string, parentId?: number): Promise<ApiResponse<NetdiskFile>> => {
    const response = await apiClient.post('/netdisk/folders', {
      name,
      parent_id: parentId
    });
    return response.data;
  },

  // 删除文件
  deleteFiles: async (fileIds: number[]): Promise<ApiResponse> => {
    const response = await apiClient.delete('/netdisk/files/delete', {
      data: { ids: fileIds }
    });
    return response.data;
  },

  // 删除单个文件（兼容性方法）
  deleteFile: async (fileId: number): Promise<ApiResponse> => {
    return driveApi.deleteFiles([fileId]);
  },

  // 移动文件
  moveFile: async (fileId: number, targetParentId?: number, newName?: string): Promise<ApiResponse> => {
    const response = await apiClient.put(`/netdisk/files/${fileId}/move`, {
      targetParentId,
      newName
    });
    return response.data;
  },

  // 复制文件
  copyFile: async (fileId: number, targetParentId?: number): Promise<ApiResponse> => {
    const response = await apiClient.post(`/netdisk/files/${fileId}/copy`, {
      targetParentId
    });
    return response.data;
  },

  // 获取下载链接
  getDownloadUrl: async (fileId: number): Promise<ApiResponse<{ downloadUrl: string }>> => {
    const response = await apiClient.get(`/netdisk/download-url/${fileId}`);
    return response.data;
  },

  // 获取下载链接（兼容性方法）
  getDownloadLink: async (fileId: number): Promise<ApiResponse<{ downloadUrl: string }>> => {
    return driveApi.getDownloadUrl(fileId);
  },

  // 上传文件检查
  checkUpload: async (md5: string, filename: string, fileSize: number, parentId?: number): Promise<ApiResponse> => {
    const response = await apiClient.post('/netdisk/upload/check', {
      md5,
      filename,
      fileSize,
      parentId
    });
    return response.data;
  },

  // 获取存储统计
  getStorageStats: async (): Promise<ApiResponse<StorageStats>> => {
    // 暂时返回模拟数据，后续可以添加真实API
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return {
      success: true,
      message: '获取存储统计成功',
      data: {
        total: 107374182400, // 100GB
        used: 32212254720,   // 30GB
        available: 75161927680, // 70GB
        files: 1247,
        folders: 89
      }
    };
  }
};